package com.vhly.bpplat.twitter.model;

import com.vhly.bpplat.util.DOMUtil;
import org.kxml2.io.KXmlParser;
import org.kxml2.kdom.Document;
import org.kxml2.kdom.Element;
import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Vector;

/**
 * Created by IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 2010-3-14
 * Time: 21:17:28
 */
public final class TwitterParser {

    private KXmlParser parser;

    private static TwitterParser outInstance;

    public static TwitterParser getInstance() {
        if (outInstance == null) {
            outInstance = new TwitterParser();
        }
        return outInstance;
    }

    private TwitterParser() {
        parser = new KXmlParser();
    }

    public Object parse(String xml) throws XmlPullParserException, IOException {

        Object ret = null;
        byte[] buf = null;
        try {
            buf = xml.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            buf = xml.getBytes();
        }
        ByteArrayInputStream bin = new ByteArrayInputStream(buf);
        parser.setInput(bin, null);
        Document doc = new Document();
        doc.parse(parser);
        bin.close();
        Element el = doc.getRootElement();
        String en = el.getName();
        if (en.equals("statuses")) {
            // public_timeline, friend_timeling etc
            ret = parseStatuses(el);
        }

        return ret;
    }

    public static Vector<Status> parseStatuses(Element el) {
        Vector<Status> ret = null;
        ret = new Vector<Status>();
        Element[] els = DOMUtil.getElementsByName(el, "", "status");
        Status st;
        for (Element en : els) {
            st = new Status();
            st.parse(en);
            ret.add(st);
        }
        return ret;
    }

    public static Vector<User> parseUsers(Element rootElement) {
        Vector<User> usrs = new Vector<User>();
        Element[] els = DOMUtil.getElementsByName(rootElement, "", "user");
        if (els != null) {
            User usr;
            for (Element en : els) {
                usr = new User();
                usr.parse(en);
                usrs.add(usr);
            }
        }
        return usrs;
    }
}
